package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;

import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityOrderOwnerDetailsBinding;
import com.sgb.kjwl.model.entity.self.AddField;
import com.sgb.kjwl.model.entity.self.OfferDetailsEntity;
import com.sgb.kjwl.model.entity.transport.OfferGoodsSourcePlaceEntity;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.transport.BiddingOrderDetailsActivity;
import com.sgb.link.view.widget.ExpandedTextView;
import com.sgb.kjwl.view.widget.TimeCountDown;
import com.sgb.kjwl.viewmodel.self.logistics.OrderOwnerDetailsModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.DateUtils;
import com.im.immodel.IMUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Describe:    接单单位详情
 * Author:  黄淋
 * Date:    2021/8/27
 */
public class OrderOwnerDetailsActivity extends AppActivity {

    private ActivityOrderOwnerDetailsBinding binding;
    private TimeCountDown timeCount;

    OrderOwnerDetailsModel viewModel;
    private String offerNo;
    private OfferDetailsEntity entity;
    private ArrayList<String> attachmentImages;

    public static void start(Context context, String offerNo) {
        Intent intent = new Intent(context, OrderOwnerDetailsActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("offerNo", offerNo);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        offerNo = getIntent().getStringExtra("offerNo");
        if (TextUtils.isEmpty(offerNo))
            finish();
        viewModel = new ViewModelProvider(this).get(OrderOwnerDetailsModel.class);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_order_owner_details);
        binding.topBar.titleView.setText("接单详情");
        binding.topBar.titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
        binding.topBar.ivBack.setOnClickListener(v -> finish());
        binding.exchangeTab.setOnClickListener(this);
        binding.callPhoneTab.setOnClickListener(this);
        binding.rightBtn.setOnClickListener(this);

        viewModel.detailsLiveData.observe(this, offerDetailsEntity -> fillData(offerDetailsEntity));
        viewModel.refreshLiveData.observe(this, aBoolean -> agreeOfferRefresh());
    }

    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            //查看附件
            case R.id.accessory:
                SeeAttachmentActivity.Companion.start(this, attachmentImages);
                break;

            //IM
            case R.id.exchange_tab:
                if (isLogin()) {
                    if (entity != null && !TextUtils.isEmpty(entity.getImAccount())) {
                       IMUtils.getInstance().buildSingleTalking(entity.getImAccount());
//                        MToast.showToast(getActivity(), "功能暂未实现");
//                        NimUIKit.startP2PSession(this, entity.getImAccount());
                    }
                } else {
                    //需要登陆
                    VerificationCodeLoginActivity.start(OrderOwnerDetailsActivity.this);
                }
                break;

            //打电话
            case R.id.call_phone_tab:
                if (!isLogin()) {
                    VerificationCodeLoginActivity.start(getActivity());
                    return;
                }
                if (entity != null && !TextUtils.isEmpty(entity.getTelphone())) {
                    showCallDialog(entity.getTelphone());
                } else {
                    ToastUtil.show(getActivity(), "无联系方式");
                }
                break;


            case R.id.right_btn:
                if (entity.getOfferStatus().equals("1")) {
                    showOfferDialog();
                } else if (entity.getOfferStatus().equals("2")) {
                    if (!TextUtils.isEmpty(entity.getOrderNo())) {
                        //跳转竞价订单详情
                        BiddingOrderDetailsActivity.start(this, entity.getOrderNo(), 0);
                    }
                }
                break;
        }
    }

    private boolean isLogin() {
        return !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
    }

    /**
     * 展示同意报价对话框
     */
    private void showOfferDialog() {
        String name = "";
        switch (entity.getOfferType()) {
            case "1"://企业
                name = entity.getCompanyName();
                break;
            case "2"://团队
                name = entity.getTeamName();
                break;
            case "3"://个人
                name = entity.getName();
                break;
        }
        new RoundDialog.Builder(this)
                .title("提示")
                .content("您确定要同意" + name + "的接单吗？确定后将生成竞价订单")
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(v -> {viewModel.agreeOrder(OrderOwnerDetailsActivity.this, entity.getNo(), entity.getSourceNo());
                })
                .show();
    }

    /**
     * 打电话弹窗
     *
     * @param phone
     */
    public void showCallDialog(String phone) {
        new RoundDialog.Builder(this)
                .title("确认呼叫")
                .content(phone)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(v -> callPhone(phone))
                .show();
    }

    public void fillData(OfferDetailsEntity entity) {
        if (entity == null) {
            ToastUtil.show(getActivity(), "未获取到数据信息");
            return;
        }
        this.entity = entity;
        //1已报价  2货主已同意  3货主未同意
        //1已报价  2待支付,3已支付(货主已同意) 4超时未支付 5货主未同意
        switch (entity.getOfferStatus()) {
            case "1":
                binding.offerStatus.setText("已接单");
                binding.offerStatus.setTextColor(Color.parseColor("#5792FD"));
                binding.rightBtn.setText("同意接单");
                binding.llRightBtn.setVisibility(View.VISIBLE);
                break;

            case "2":
                binding.offerStatus.setText("已同意");
                binding.offerStatus.setTextColor(Color.parseColor("#06C764"));
                binding.rightBtn.setText("查看订单");
                binding.llRightBtn.setVisibility(View.VISIBLE);
                break;

            case "5":
                binding.offerStatus.setText("未同意");
                binding.offerStatus.setTextColor(Color.parseColor("#FF2928"));
                binding.llRightBtn.setVisibility(View.GONE);
                break;
        }

        /**
         * 报价单位信息
         */
        if (!TextUtils.isEmpty(entity.getHeadImage())) {
            Glide.with(getActivity())
                    .load(entity.getHeadImage())
                    .into(binding.diverHead);
        }
        if (!TextUtils.isEmpty(entity.getName())) {
            binding.contactName.setText(entity.getName());
        } else {
            binding.contactName.setText("");

        }
        if (!TextUtils.isEmpty(entity.getTelphone())) {
            binding.phoneNum.setText(entity.getTelphone());
            binding.phoneNum.setOnClickListener(view -> showCallDialog(entity.getTelphone()));
        }

        if (!TextUtils.isEmpty(entity.getOfferType())) {
            switch (entity.getOfferType()) {
                case "1"://企业
                    binding.companyInfoLayout.setVisibility(View.VISIBLE);
                    binding.companyName.setText(!TextUtils.isEmpty(entity.getCompanyName()) ? entity.getCompanyName() : "/");
                    binding.offerArticle.setText(!TextUtils.isEmpty(entity.getCompanyName()) ? entity.getCompanyName() : "");
                    binding.creditCode.setText(!TextUtils.isEmpty(entity.getCreditCode()) ? entity.getCreditCode() : "/");
                    binding.companyType.setText(!TextUtils.isEmpty(entity.getCompanyType()) ? entity.getCompanyType() : "/");
                    binding.registeredAssets.setText(!TextUtils.isEmpty(entity.getRegisteredCapital()) ? entity.getRegisteredCapital() + "元" : "/");
                    binding.setUpDate.setText(!TextUtils.isEmpty(entity.getEstablishmentDate()) ? DateUtils.formatDate(entity.getEstablishmentDate(), "yyyy-MM-dd") : "/");
                    binding.companyAddress.setText(!TextUtils.isEmpty(entity.getBusinessAddress()) ? entity.getBusinessAddress() : "/");
                    binding.carInfo.setVisibility(View.GONE);
                    binding.carInfoHint.setVisibility(View.GONE);
                    binding.carLocation.setVisibility(View.GONE);
                    binding.carLocationHint.setVisibility(View.GONE);
                    break;

                case "2"://团队
                    binding.teamInfoLayout.setVisibility(View.VISIBLE);
                    binding.teamName.setText(!TextUtils.isEmpty(entity.getTeamName()) ? entity.getTeamName() : "/");
                    binding.offerArticle.setText(!TextUtils.isEmpty(entity.getTeamName()) ? entity.getTeamName() : "");
                    binding.teamBusiness.setText(!TextUtils.isEmpty(entity.getBusinessTypeNo()) ? entity.getBusinessTypeNo() : "/");
                    binding.teamPeopleNum.setText(entity.getScale() + "人");
                    binding.teamAddress.setText(!TextUtils.isEmpty(entity.getBusinessAddress()) ? entity.getBusinessAddress() : "/");
                    binding.carInfo.setVisibility(View.GONE);
                    binding.carInfoHint.setVisibility(View.GONE);
                    binding.carLocation.setVisibility(View.GONE);
                    binding.carLocationHint.setVisibility(View.GONE);
                    break;

                case "3"://个人
                    binding.offerArticle.setText(!TextUtils.isEmpty(entity.getName()) ? entity.getName() : "");
                    //车辆信息
                    String carInfo = "";
                    //车牌
                    if (!TextUtils.isEmpty(entity.getCarNumber()))
                        carInfo += entity.getCarNumber();
                    //车型
                    if (!TextUtils.isEmpty(entity.getCarTypeName()))
                        carInfo += "/" + entity.getCarTypeName();
                    //栏高
                    if (!TextUtils.isEmpty(entity.getHeightHurdle()))
                        carInfo += "/" + "栏高" + NumberUtil.trim0(entity.getHeightHurdle()) + "米";
                    //车长
                    if (!TextUtils.isEmpty(entity.getCarLenName()))
                        carInfo += "/" + entity.getCarLenName();
                    //是否自卸
                    if (!TextUtils.isEmpty(entity.getIsDump()))
                        carInfo += "/" + entity.getIsDump();
                    if (TextUtils.isEmpty(carInfo)) {
                        binding.carInfo.setVisibility(View.GONE);
                        binding.carInfoHint.setVisibility(View.GONE);
                    } else {
                        binding.carInfo.setText(StringUtil.removeChar(carInfo, "/"));
                        binding.carInfo.setVisibility(View.VISIBLE);
                        binding.carInfoHint.setVisibility(View.VISIBLE);
                    }

                    String address = "";
//                    if (!TextUtils.isEmpty(entity.getProvinceName()))
//                        address += entity.getProvinceName();
//                    if (!TextUtils.isEmpty(entity.getCityName()))
//                        address += entity.getCityName();
//                    if (!TextUtils.isEmpty(entity.getDistrictName()))
//                        address += entity.getDistrictName();
                    if (!TextUtils.isEmpty(entity.getDetailAddress()))
                        address += entity.getDetailAddress();
                    binding.carLocation.setText(!TextUtils.isEmpty(address) ? address : "/");
                    binding.carLocation.setVisibility(View.VISIBLE);
                    binding.carLocationHint.setVisibility(View.VISIBLE);
                    break;
            }
        }

        ///////////////////////货源信息
        if (entity.getPlace() != null) {
            OfferGoodsSourcePlaceEntity placeEntity = entity.getPlace();
            //发货起始地
            String addStr = "";
            if (!TextUtils.isEmpty(placeEntity.getCityName())) {
                addStr += placeEntity.getCityName() + " ";
            }
            if (!TextUtils.isEmpty(placeEntity.getDistrictName())) {
                addStr += placeEntity.getDistrictName() + " → ";
            } else {
                addStr += " → ";
            }
            if (!TextUtils.isEmpty(placeEntity.getDestCityName())) {
                addStr += placeEntity.getDestCityName() + " ";
            }
            if (!TextUtils.isEmpty(placeEntity.getDestDistrictName())) {
                addStr += placeEntity.getDestDistrictName();
            }
            binding.transportPath.setText(addStr);

            //运程
            if (!TextUtils.isEmpty(placeEntity.getTotalDistance())) {
                if (Double.valueOf(placeEntity.getTotalDistance()) < 1000) {
                    binding.haul.setText("运程：1km以内");
                } else {
                    binding.haul.setText(String.format("运程：约%skm", StringUtil.fromatUpDistance(placeEntity.getTotalDistance()) + ""));
                }
            }
        }

        String goodsInfo = "";
        if (!TextUtils.isEmpty(entity.getGoodsTypeName())) {
            goodsInfo += entity.getGoodsTypeName();
        }
        if (!TextUtils.isEmpty(entity.getSecondGoodsTypeName())){
            goodsInfo+="/"+entity.getSecondGoodsTypeName();
        }
        if (!TextUtils.isEmpty(entity.getWeight())) {
            goodsInfo += NumberUtil.trim0(entity.getWeight()) + "吨 ";
        }
        if (!TextUtils.isEmpty(entity.getVolume())) {
            goodsInfo += NumberUtil.trim0(entity.getVolume()) + "方";
        }
        if (!TextUtils.isEmpty(goodsInfo)) {
            binding.goodsInfo.setText(goodsInfo);
        }

        if (!TextUtils.isEmpty(entity.getSourceAllFreight())) {
            binding.freightPrice.setText(NumberUtil.trim0(entity.getSourceAllFreight()) + "元");
        }

        //司机报价信息
        if (!TextUtils.isEmpty(entity.getCreateTime())) {
            binding.offerTime.setText(DateUtils.formatDate(String.valueOf(entity.getCreateTime()), ""));
        }
        binding.freightOffer.setText(!TextUtils.isEmpty(entity.getFreight()) ? NumberUtil.trim0(entity.getFreight()) + "元/吨" : "/");
        binding.freightUnit.setText(!TextUtils.isEmpty(entity.getSourceFreight()) ? NumberUtil.trim0(entity.getSourceFreight()) + entity.getFreightUnit() : "/");
        binding.freightPrice.setText(!TextUtils.isEmpty(entity.getSourceAllFreight()) ? NumberUtil.trim0(entity.getSourceAllFreight()) + "元" : "/");

        binding.contactInfo.setText(!TextUtils.isEmpty(entity.getContrcts()) ? entity.getContrcts() + "  " : "");
        if (!TextUtils.isEmpty(entity.getContrctsNumber())) {
            binding.contactNumber.setText(entity.getContrctsNumber());
            binding.contactNumber.setOnClickListener(view -> showCallDialog(entity.getContrctsNumber()));
        }

        if (!TextUtils.isEmpty(entity.getNote())) {
            binding.remarkLayout.setVisibility(View.VISIBLE);
            binding.contentView.setText(entity.getNote());
            new ExpandedTextView().showTextPick(binding.contentView, binding.expandView);
        } else {
            binding.remarkLayout.setVisibility(View.GONE);
        }

        if (entity.getDiyField() != null && entity.getDiyField().size() > 0) {
            binding.customContent.setVisibility(View.VISIBLE);
            binding.customContent.removeAllViews();
            for (int i = 0; i < entity.getDiyField().size(); i++) {
                AddField itemEntity = entity.getDiyField().get(i);
                if (!TextUtils.isEmpty(itemEntity.getValue()))
                    addCustomLayout(binding.customContent, itemEntity);
            }
        } else {
            binding.customContent.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(entity.getAccessory())) {
            List<String> images = Arrays.asList(entity.getAccessory().split(","));
            attachmentImages = new ArrayList<>(images);
        } else {
            attachmentImages = new ArrayList();
        }

        if (attachmentImages.size() == 0) {
            binding.accessoryHint.setVisibility(View.GONE);
            binding.accessory.setVisibility(View.GONE);
        } else {
            binding.accessoryHint.setVisibility(View.VISIBLE);
            binding.accessory.setVisibility(View.VISIBLE);
        }
        binding.accessory.setOnClickListener(this::onMultiClick);

        String inTime = DateUtils.stampToDay5(entity.getInTime());
        binding.arriveTime.setText(TextUtils.isEmpty(inTime) ? "/" : inTime);

        binding.scrollView.setVisibility(View.VISIBLE);
        binding.bottomBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeCount != null)
            timeCount.cancel();
    }

    /**
     * 为自定义字段添加布局
     *
     * @param content
     * @param entity
     */
    private void addCustomLayout(LinearLayout content, AddField entity) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.custom_field_layout, null);
        TextView remark_hint = view.findViewById(R.id.remark_hint);
        TextView content_tv = view.findViewById(R.id.content_tv);
        TextView expand_tv = view.findViewById(R.id.expand_tv);
        if (!TextUtils.isEmpty(entity.getKey())) {
            remark_hint.setText(entity.getKey());
        } else
            remark_hint.setText("自定义");

        content_tv.setText(entity.getValue());
        new ExpandedTextView().showTextPick(content_tv, expand_tv);
        content.addView(view);
    }

    @Override
    protected void onResume() {
        super.onResume();
        viewModel.getOfferOwnerDetails(this, offerNo);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
//        DaggerSelfComponent.builder()
//                .appComponent(appComponent)
//                .selfModule(new SelfModule(this))
//                .build().inject(this);

    }

    /**
     * 货主同意同意报价
     */
    public void agreeOfferRefresh() {
        viewModel.getOfferOwnerDetails(this, offerNo);
        EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_REFRESH_ORDER_OWNER_PAGE));
        EventBus.getDefault().post(LogisticsEvent.make(EventConstant.EVENT_GOODS_AGREED_OFFER, null));
    }
}
